package cn.edu.stu.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Karl
 * @Date 2022/12/12 - 14:20
 */
public class JWTUtil {
    private JWTUtil(){}


    private static final String PRIVATE_KEY="!YXG4$%*^fAGENi$R";

    /**
     * 生成默认时间为1分钟的token
     * @param map 数据
     * @return
     */
    public static String createToken(Map<String,String> map){
        return createToken(map,60);
    }

    public static String createToken(Map<String,String> map,int expirationSeconds){
        //指定过期时间为1分钟
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,expirationSeconds);
        //存储header的哈希表
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        //签名
        String token = builder.withExpiresAt(instance.getTime())  //设置过期时间
                .sign(Algorithm.HMAC256(PRIVATE_KEY));
        return token;
    }

    /**
     * 验证token的合法性
     * @param token
     * @return
     */
    public static Map<String,String> verify(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(PRIVATE_KEY)).build().verify(token);
        Map<String, Claim> claims = verify.getClaims();
        Map<String,String> map = new HashMap<>();
        claims.forEach((k,v)->{
            map.put(k,v.asString());
        });
        return map;
    }

}
